package com.gxa.admin.controller;

import com.gxa.admin.utils.TencentCOS;
import com.gxa.core.result.Result;
import com.gxa.core.result.ResultUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 */
@Controller
@ResponseBody
@Slf4j
@RequestMapping("/upload")
public class UploadController {

    //配置限制运行文件上传的格式
    private static  final List<String> extList= Arrays.asList(".jpg",".png",".bmp");


    @RequestMapping(value = "/image",method = RequestMethod.POST)
    public Result upload(@RequestParam("file") MultipartFile image) throws IOException {

        String fileName = image.getOriginalFilename();

        log.debug("上传文件的名字为:{}",fileName);

        //获取上传文件的后缀
        String ext=fileName.substring(fileName.lastIndexOf("."));

        log.debug("上传文件的扩展名:{}",ext);

        if(!extList.contains(ext)){
            //格式不合法
            log.error("格式不合法:{}",ext);
           return ResultUtils.buildFail(20001, "上传图片的格式不合法");
        }

        //生成新的文件名
        String newFileName= UUID.randomUUID().toString().replace("-","")+ext;


        //创建临时的File对象
        File file=File.createTempFile("image-",newFileName);

        //把图片存储到临时的File对象中
        image.transferTo(file);

        //把临时的File发送给腾讯云服务器进行存储
        String name = TencentCOS.uploadFile(file, "caffee-go");

        log.info("上传到腾讯云服务器图片:{}",name);

        //删除临时的file对象
        if(file.exists()){
            file.delete();
        }
        //返回图片的访问地址
        return ResultUtils.buildSuccess("https://caffee-go-1324835666.cos.ap-chengdu.myqcloud.com/" + name);
    }

}
